package 力扣;



/**
 * @author yyq
 * @create 2022-04-15 10:59
 */
public class leetcode617 {
    public static void main(String[] args) {
        TreeNode root1=new TreeNode(1);
        TreeNode root2=new TreeNode(1);
        root2.right=new TreeNode(2);
        mergeTrees(root1,root2);
    }
    public static TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if(root1==null&&root2==null) return null;
        int root1val=0;
        int root2val=0;

        if(root1!=null) root1val=root1.val;
        if(root2!=null) root2val=root2.val;
        TreeNode root = new TreeNode(root1val+root2val);
        ToATree(root, root1,root2);
        return root;
    }

    private static void ToATree(TreeNode root, TreeNode root1, TreeNode root2) {
        if(root1==null&&root2==null) return;
        int root1left = 0;
        int root1right = 0;
        int root2left = 0;
        int root2right = 0;
        if(root1!=null){
            if (root1.left!=null) root1left = 1;
            if(root1.right!=null) root1right = 1;
        }
        if(root2!=null){
            if (root2.left!=null) root2left = 1;
            if(root2.right!=null) root2right = 1;
        }

        // 构建左子树
        if(root1left==1&&root2left==1){
            root.left = new TreeNode(root1.left.val+root2.left.val);
            ToATree(root.left,root1.left,root2.left);
        }
        else if(root1left==0&&root2left==1) {
            root.left = new TreeNode(root2.left.val);
            ToATree(root.left,null,root2.left);
        }
        else if(root1left==1&&root2left==0) {
            root.left = new TreeNode(root1.left.val);
            ToATree(root.left,root1.left,null);
        }

        // 构建右子树
        if(root1right==1&&root2right==1){
            root.right = new TreeNode(root1.right.val+root2.right.val);
            ToATree(root.right,root1.right,root2.right);
        }
        else if(root1right==0&&root2right==1) {
            root.right = new TreeNode(root2.right.val);
            ToATree(root.right,null,root2.right);
        }
        else if(root1right==1&&root2right==0) {
            root.right = new TreeNode(root1.right.val);
            ToATree(root.right,root1.right,null);
        }

    }
}
